package com.nbcio.modules.erp.pref.controller;

import com.nbcio.common.core.domain.R;
import com.nbcio.common.satoken.utils.LoginHelper;
import com.nbcio.modules.erp.pref.domain.ErpUserPref;
import com.nbcio.modules.erp.pref.service.IErpUserPrefService;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

@Slf4j
@Tag(name = "ERP用户偏好")
@RestController
@RequestMapping("/erp/pref")
@RequiredArgsConstructor
public class ErpUserPrefController {

    private final IErpUserPrefService prefService;

    @GetMapping
    public R<String> get(@RequestParam String module, @RequestParam String key) {
        try {
            Long userId = LoginHelper.getUserId();
            ErpUserPref pref = prefService.getByUserAndKey(userId, module, key);
            if (pref == null || pref.getPrefValue() == null) {
                return R.ok(null);
            }
            // 确保返回字符串格式：prefValue 可能是 String 或 Object（MySQL JSON 类型）
            Object prefValueObj = pref.getPrefValue();
            String prefValue;
            if (prefValueObj instanceof String) {
                prefValue = (String) prefValueObj;
            } else {
                // 如果是对象（Map/List），转换为 JSON 字符串
                prefValue = com.nbcio.common.json.utils.JsonUtils.toJsonString(prefValueObj);
            }
            // 如果是空字符串，返回 null
            if (prefValue == null || prefValue.trim().isEmpty()) {
                return R.ok(null);
            }
            return R.ok(prefValue);
        } catch (Exception e) {
            log.error("获取用户偏好失败: module={}, key={}", module, key, e);
            return R.fail("获取用户偏好失败: " + e.getMessage());
        }
    }

    @PostMapping
    public R<Boolean> save(@RequestParam String module, @RequestParam String key, @RequestBody String value) {
        Long userId = LoginHelper.getUserId();
        ErpUserPref exist = prefService.getByUserAndKey(userId, module, key);
        if (exist == null) {
            ErpUserPref pref = new ErpUserPref();
            pref.setId(java.util.concurrent.ThreadLocalRandom.current().nextLong(Long.MAX_VALUE));
            pref.setUserId(userId);
            pref.setModule(module);
            pref.setPrefKey(key);
            pref.setPrefValue(value);
            return R.ok(prefService.save(pref));
        } else {
            exist.setPrefValue(value);
            return R.ok(prefService.updateById(exist));
        }
    }
}


